import React, { useState, useEffect, useRef } from "react";
import { Button, message } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { PlusOutlined } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";
import { useModel } from "umi";
import {
  ModalForm,
  ProFormText,
  ProFormDependency,
  ProFormSwitch,
  ProFormCascader,
  ProFormSelect,
} from "@ant-design/pro-form";

import {
  fetchList,
  add,
  update,
  updateStatus,
  remove,
} from "@/api/hospital_account";

import { getHospitalTreeList } from "@/api/hospital";

import {
  disableStatusOptions,
  typeAdminOptions,
  typeOptions,
  filterTypeOptions,
} from "@/const";
import useRemove from "@/hooks/useRemove";
import useUpdateStatus from "@/hooks/useUpdateStatus";
import { useHospitalColumns } from "@/hooks/useHospital";

const modalLayout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};

const Admin = () => {
  const { initialState, setInitialState } = useModel("@@initialState");
  const actionRef = useRef();
  const formRef = useRef();
  const [hospitalList, setHospitalList] = useState([]);

  // 质控中心
  const fetchHospitalList = async (data) => {
    const res = await getHospitalTreeList(data);
    setHospitalList(res.data);
  };

  const getName = (type) => {
    const obj = { 1: "质控中心", 2: "医院", 3: "检验所", 4: "医院（PC）" };
    return obj[type];
  };

  // 新增和修改
  const renderModalForm = (actionType, record) => {
    // actionType 1=新增 2=修改
    const title = actionType === 1 ? "新增账号" : "修改账号";

    const handleAddOrUpdate = async (fields) => {
      console.log(fields);
      const obj = {
        1: 2, // 质控中心员传2
        2: 3, // 医院管理员传3
        3: 6, // 检验所管理员传6
        4: 9, // 医院（PC）传9
      };
      const postData = {
        ...fields,
        id: record?.admin?.id,
        status: fields.status ? 1 : 0,
        hospitalId: "",
        roleIds: [obj[fields.type]],
      };
      if (fields.type === 2) {
        postData.hospitalPid = fields.hospitalId?.[0];
        postData.hospitalId = fields.hospitalId?.[1];
      } else {
        postData.hospitalId = fields.hospitalId;
      }
      let func = add;
      if (record?.admin?.id) {
        func = update;
      }
       const res = await func(postData);
      if (res.data) {
        message.success(title + "成功");
        if (actionType === 1) {
          formRef.current?.resetFields();
        }
        actionRef?.current.reload();
        return true; // 关闭弹框
      }
    };

    const createAccountOptions = () => {
      if (initialState?.currentUser?.type === 0) {
        return actionType === 1 ? typeAdminOptions : typeOptions;
      } else {
        return typeOptions;
      }
    };

    return (
      <ModalForm
        key={title}
        formRef={formRef}
        layout="horizontal"
        {...modalLayout}
        title={title}
        width={600}
        trigger={
          actionType === 1 ? (
            <Button key="button" icon={<PlusOutlined />} type="primary">
              添加
            </Button>
          ) : (
            <Button
              style={{ marginRight: 10 }}
              size="small"
              key="update"
              type="primary"
            >
              修改
            </Button>
          )
        }
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
        }}
        onFinish={async (values) => {
          return await handleAddOrUpdate(values);
        }}
        initialValues={{
          ...record?.admin,
          password: record?.admin?.password,
          confirmPwd: record?.admin?.password,
          status: record?.admin?.status == 1,
          hospitalId: record?.admin?.hospitalLevels
            ? record?.admin?.hospitalLevels
            : [],
        }}
      >
        <ProFormSelect
          name="type"
          label="账号类型"
          disabled={actionType === 2}
          allowClear
          fieldProps={{
            options: createAccountOptions(),

            onChange: (type) => {
              fetchHospitalList({
                type,
              });
              formRef.current?.setFieldsValue({
                hospitalId: null,
              });
            },
          }}
          rules={[{ required: true, message: "请选择账号类型" }]}
        />

        {actionType === 1 ? (
          <ProFormDependency name={["type"]}>
            {({ type }) => {
              if (type === 1) {
                return (
                  <ProFormSelect
                    name="hospitalId"
                    label="质控中心"
                    allowClear
                    fieldProps={{
                      options: hospitalList,
                      fieldNames: {
                        label: "name",
                        value: "id",
                      },
                    }}
                    rules={[{ required: true, message: "请选择机构" }]}
                  />
                );
              }
              if (type === 2) {
                return (
                  <ProFormCascader
                    name="hospitalId"
                    label="医院"
                    allowClear
                    fieldProps={{
                      // changeOnSelect: true,  // 每一级都可选
                      options: hospitalList,
                      fieldNames: {
                        value: "id",
                        label: "name",
                        children: "children",
                      },
                    }}
                    rules={[{ required: true, message: "请选择医院" }]}
                  />
                );
              }
              if (type === 3) {
                return (
                  <ProFormSelect
                    name="hospitalId"
                    label="检验所"
                    allowClear
                    fieldProps={{
                      options: hospitalList,
                      fieldNames: {
                        value: "id",
                        label: "name",
                      },
                    }}
                    rules={[{ required: true, message: "请选择检验所" }]}
                  />
                );
              }
            }}
          </ProFormDependency>
        ) : (
          <ProFormText
            disabled
            label={getName(record?.admin?.type)}
            name="hospitalName"
          />
        )}

        <ProFormText
          label="姓名"
          name="name"
          rules={[
            { required: true, message: "请输入姓名" },
            {
              max: 20,
              message: "最长为20位",
            },
          ]}
        />

        <ProFormText
          label="账号"
          name="account"
          disabled={actionType === 2}
          rules={[
            { required: true, message: "请输入账号" },
            {
              max: 20,
              message: "最长为20位",
            },
          ]}
        />
        <ProFormText
          label="电话号码"
          name="phone"
          placeholder="请输入电话号码"
          rules={[
            {
              required: true,
              message: "请输入电话号码",
            },
            {
              pattern:
                /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/,
              message: "电话号码格式错误",
            },
          ]}
        />
        <ProFormText.Password
          label="密码"
          name="password"
          placeholder="请输入密码"
          rules={[
            {
              required: true,
              message: "请输入密码",
            },
            {
              min: 6,
              message: "密码最短6位",
            },
            {
              max: 12,
              message: "密码最长为12位",
            },
            // {
            //   pattern: /^[a-zA-Z]\w{5,17}$/,
            //   message: "密码格式错误",
            // },
          ]}
        />
        <ProFormDependency name={["password"]}>
          {({ password }) => {
            return (
              <ProFormText.Password
                label="确认密码"
                name="confirmPwd"
                placeholder="请输入密码"
                rules={[
                  {
                    required: true,
                    message: "请输入密码",
                  },
                  {
                    validator(_, value) {
                      if (!value || password === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error("两次密码不一致"));
                    },
                  },
                ]}
              />
            );
          }}
        </ProFormDependency>

        <ProFormSwitch
          name="status"
          label="状态"
          fieldProps={{
            checkedChildren: "启用",
            unCheckedChildren: "停用",
          }}
        />
      </ModalForm>
    );
  };

  const columns = [
    {
      title: "序号",
      valueType: "index",
    },
    {
      title: "姓名",
      dataIndex: "name",
      render: (_, record) => {
        return record.admin?.name;
      },
    },
    {
      title: "账号",
      dataIndex: "account",
      render: (_, record) => {
        return record.admin?.account;
      },
    },
    {
      title: "电话号码",
      dataIndex: "account",
      render: (_, record) => {
        return record.admin?.phone || '-';
      },
    },
    {
      title: "账号类型",
      dataIndex: "type",
      valueType: "select",
      fieldProps: {
        options: typeOptions,
      },
      render: (_, record) => {
        return filterTypeOptions(record.admin?.type);
      },
    },
    {
      title: "质控中心/医院/检验所",
      dataIndex: "hospitalName",
      search: false,
      render: (_, record) => {
        return record?.admin?.hospitalName;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      valueType: "select",
      fieldProps: {
        options: disableStatusOptions,
      },
      search: false,
      render: (_, record) => {
        return useUpdateStatus(updateStatus, record, actionRef, "admin");
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      search: false,
      render: (_, record) => {
        return record?.admin?.createTime;
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      width: 240,
      render: (_, record) => [
        renderModalForm(2, record),
        useRemove(remove, record, actionRef, { ids: record?.admin?.id }),
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={(record) => record.admin.id}
        search={{
          labelWidth: 80,
          defaultCollapsed: false,
        }}
        request={fetchList}
        columns={columns}
        toolBarRender={() => [renderModalForm(1)]}
      />
    </PageContainer>
  );
};

export default Admin;
